<template>
  <edit-nav-component title="编辑和发布我的贴文" />
  <div style="padding:20px 0;width:1200px;margin:auto">
    发布至：
    <!-- <el-checkbox-group v-model="postAreas">
      <el-checkbox label="本校" checked />
      <el-checkbox label="全国" />
    </el-checkbox-group> -->
    <el-radio-group v-model="articleExtent">
      <el-radio label="本校">本校</el-radio>
      <el-radio label="全国">全国</el-radio>
      <el-radio label="同时">同时</el-radio>
    </el-radio-group>
    &nbsp;&nbsp;
    <el-button type="success" @click="postArticle(true)">立即发布</el-button>
    <el-button type="info" @click="postArticle(false)">存入草稿</el-button>
    <el-button type="danger" @click="abandonArticle()">取消发布</el-button>
    <div style="padding:10px"></div>
    <div style="display:flex;width:100%">
      <div style="width:100%;padding-right:20px">
        <el-input type="textarea" :rows="1" placeholder="文章标题" v-model="articleTitle" />
        <div style="padding:10px"></div>
        <el-input type="textarea" :rows="3" placeholder="文章摘要" v-model="articleDesc" />
      </div>
      <div class="article_cover_container" @click="selectCover">
        <input type="file" style="display:none" name="articleCover" @change="fileChange($event)"
          id="article_cover_input">
        <img v-if="imgSrc != null" :src="imgSrc" alt="">
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </div>
    </div>

    <div style="width:100%;margin:20px auto">
      <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
          :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig"
          :mode="mode" @onCreated="handleCreated" />
      </div>
    </div>
  </div>
</template>

<script>
import EditNavComponent from '@/components/edit/EditNavComponent.vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import fetchutil from "../assets/js/fetchutil";

import { onBeforeUnmount, shallowRef } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { EditNavComponent, Editor, Toolbar },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    // const valueHtml = ref('<p>hello</p>')

    // 模拟 ajax 异步获取内容
    // onMounted(() => {
    //   setTimeout(() => {
    //     valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>'
    //   }, 1500)
    // })
    const toolbarConfig = {}
    const editorConfig = { placeholder: '正文' }
    const resourceId = new Date().getTime() + ''

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
      // console.log(editorRef.value.getConfig());
      let config = editorRef.value.getConfig()
      config.MENU_CONF['uploadImage'] = {
        async customUpload(file, insertFn) {
          let fileName = file.name
          let fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
          let acceptTypeList = ['jpg', 'jpeg', 'gif', 'png', 'webp']
          let typeVerified = false
          acceptTypeList.forEach(el => {
            if (el == fileType) {
              typeVerified = true
              return
            }
          })
          if (!typeVerified) {
            alert('请选择图片类型的文件')
            return
          }
          let formData = new FormData()
          formData.append('resourceFile', file)
          formData.append("attach", new Blob([JSON.stringify({
            resourceId: resourceId + '-' + Math.floor(Math.random() * 10000),
            type: fileType
          })], { type: "application/json" }));
          fetchutil.uploadFile('/article/upload_article_resource', formData, callback => {
            // console.log(callback)
            if (callback.success) {
              insertFn(callback.msg, null, null)
            } else {
              alert(callback.msg)
            }
          })
        }
      }
    }
    return {
      resourceId,
      editorRef,
      valueHtml: '',
      mode: 'simple', // 或 'simple'
      toolbarConfig,
      editorConfig,
      handleCreated
    };
  },
  data() {
    return {
      // postAreas: [],
      imgSrc: null,
      imgFile: null,
      articleId: 0,
      articleTitle: '',
      articleDesc: '',
      articleExtent: '本校',
      editModel: false
    }
  },
  created() {
    let articleId = this.getQueryVariable('article_id')
    if (!articleId) return

    this.$fetchutil.get('/browse/article_detail?articleId=' + this.getQueryVariable('article_id'), data => {
      let article = data.data
      document.title = '编辑我的贴文————' + article.articleTitle
      this.editModel = true
      this.valueHtml = article.articleContent
      this.articleId = article.articleId
      this.articleTitle = article.articleTitle
      this.articleDesc = article.articleDesc
      this.articleExtent = article.articleExtent
      this.imgSrc = article.articleCoverUrl
      this.resourceId = article.articleResourceId
    })
  },
  methods: {
    getQueryVariable(variable) {
      var query = window.location.search.substring(1);
      var vars = query.split("&");
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
      }
      return (false);
    },
    onArticleCoverChange() {
      // console.log('coverFile');
    },
    selectCover() {
      document.getElementById('article_cover_input').click()
    },
    fileChange(event) {
      this.imgSrc = window.URL.createObjectURL(event.target.files[0])
      this.imgFile = event.target.files[0]
    },
    postArticle(status) {
      let formData = new FormData()
      if (this.imgFile == null) {
        if (!this.editModel) {
          this.$ElMessage({
            message: '请上传贴文封面',
            type: 'error'
          })
          return
        }
      } else {
        formData.append('resourceFile', this.imgFile)
      }
      if (this.articleTitle == '' || this.articleDesc == '' || this.valueHtml == '') {
        this.$ElMessage({
          message: '请将贴文填写完整',
          type: 'error'
        })
        return
      }
      formData.append("article", new Blob([JSON.stringify({
        articleId: this.articleId,
        articleTitle: this.articleTitle,
        articleDesc: this.articleDesc,
        articleContent: this.valueHtml,
        articleStatus: status ? '已发布' : '草稿',
        articleResourceId: this.resourceId,
        articleExtent: this.articleExtent
      })], { type: "application/json" }));
      fetchutil.uploadFile(!this.editModel ? '/article/upload_article' : '/article/update_article',
        formData, callback => {
          this.$ElMessage({
            message: callback.msg,
            type: callback.success ? "success" : "error",
          })
          if (callback.success) {
            if (this.editModel) document.location.replace('/article.html?id=' + this.articleId)
            else document.location.replace('/article.html?id=' + callback.data)
          }
        })
    },
    abandonArticle() {
      window.close()
    }
  },
  watch: {
    // postAreas(to) {
    //   if (to.length == 2) this.articleExtent = '同时'
    //   else this.articleExtent = to[0]
    // }
  }
}
</script>

<style scoped>
.article_cover_container {
  display: block;
  width: 120px;
  border-radius: 6px;
  border: 1px dashed var(--el-border-color);
  height: 120px;
}

.article_cover_container:hover {
  border-color: var(--el-color-primary);
}

.article_cover_container img {
  width: 100%;
  height: 100%;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>